<template>
  <div class="container">
    <Header :getGoods="getGoods"  />
    <main>
      <div class="main-upper">
        <div v-if="userVo?.avatarPath" class="user-avatar">
          <img :src="userVo.avatarPath" alt="User Avatar" />
        </div>
        <div class="container-userInfo">
          <div class="username-collect">
            <button class="upUsername">{{ userVo?.username }}</button>
            <div v-show="!isCollect" class="goodsDetail-collect-add" @click="addCollect">
              <el-icon><Star /></el-icon>
            </div>
            <div v-show="isCollect" class="goodsDetail-collect-delete" @click="deleteCollect">
              <el-icon><StarFilled /></el-icon>
            </div>
          </div>
          <div class="user-info">
            <div class="nowAddress">
              <p><strong>地址:</strong> {{ userVo?.address }}</p>
            </div>
            <div class="nowAccountAge">
              <p><strong>账户年龄:</strong> {{ userVo?.accountAge }} 年</p>
            </div>
          </div>
        </div>
        <div class="action-buttons-group">
          <button class="follow-seller-button" @click="follow">关注卖家</button>
          <button class="contact-seller-button" @click="ContactTheSeller" >联系卖家</button>
        </div>
      </div>
      <div class="main-lower">
        <div class="main-left">
          <div class="image-slider">
            <button class="prev-button" @click="prevImage"><</button>
            <img :src="goodsImages[currentImageIndex]?.goodsImg" alt="Goods Image" />
            <button class="next-button" @click="nextImage">></button>
            <div class="image-info">
              <span
                v-for="(image, index) in goodsImages"
                :key="index"
                class="dot"
                :class="{ active: index === currentImageIndex }"
                :style="{ fontSize: index === currentImageIndex ? '20px' : '14px' }"
              >•</span>
            </div>
          </div>
        </div>
        <div class="main-center">
          <div class="product-info">
            <h2>{{ goods?.name }}</h2>
            <h1>{{ goods?.intro }}</h1>
            <p><strong>发布时间:</strong> {{ goods?.createTime }}</p>

            <table class="goods-details-table">
              <tr>
                <td><strong>类型:</strong>{{categories}}</td>
                <td><strong>平台:</strong> {{ goods?.platform }}</td>
                <td><strong>包邮:</strong> {{ goods?.freePost }}</td>
              </tr>
              <tr>
                <td><strong>版本:</strong> {{ goods?.version }}</td>
                <td><strong>包装:</strong> {{ goods?.packa }}</td>
                <td><strong>成色:</strong> {{ goods?.fineness }}</td>
              </tr>
            </table>
            <div class="comments-section">
              <div class="comments-display">
                <div v-for="comment in comments" :key="comment.id" class="comments-group">
                  <div class="comments__comment">
                    <img v-if="comment.avatar" :src="comment.avatar" alt="User Avatar" class="avatar" />
                    <div>
                      <p>{{ comment.user }}: {{ comment.content }}
                        <button class="reply-button" @click="replyToComment(comment)">回复</button>
                      </p>
                      <div v-if="comment.replies.length">
                        <div
                          v-for="(reply, index) in comment.replies"
                          :key="reply.id"
                          v-show="index < (comment.visibleRepliesCount ?? 1)"
                          class="comments__reply"
                        >
                          <img v-if="reply.avatar" :src="reply.avatar" alt="User Avatar" class="avatar" />
                          <div>
                            <p>{{ reply.user }}: {{ reply.content }}
                              <button class="reply-button" @click="replyToComment(reply)">回复</button>
                            </p>
                          </div>
                        </div>
                        <button
                          v-if="comment.replies.length > (comment.visibleRepliesCount ?? 1)"
                          @click="showMoreReplies(comment)"
                          aria-label="Show more replies"
                          class="show"
                        >
                          展示更多 ({{ comment.replies.length - (comment.visibleRepliesCount ?? 1) }} 条评论)
                        </button>
                        <button
                          v-else-if="comment.replies.length > 1"
                          @click="showLessReplies(comment)"
                          aria-label="Show fewer replies"
                          class="back"
                        >
                          收起
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="comment-input">
                <textarea v-model="newComment" placeholder="添加评论..."></textarea>
                <button @click="submitComment">发送</button>
              </div>
            </div>
          </div>
          <div class="action-buttons">
            <button class="buy-now-button" @click="buy">￥{{ goods?.price }}立刻购买</button>
            <button class="add-to-cart-button" @click="addToCar">添加到购物车</button>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';
import Header from './Header.vue';
import '../css/goodsDetail.css';
import { useRouter } from 'vue-router';

interface Goods {
  id: number;
  name: string;
  imgPath: string;
  price: number;
  blurb: string;
  intro: string;
  categoriesId: string;
  platform: string;
  createTime: string;
  updateTime: string;
  createUser: string;
  updateUser: string;
  freePost: string;
  version: string;
  packa: string;
  fineness: string;
}
interface GoodsImage {
  id: number;
  goodsId: number;
  goodsImg: string;
}
interface Comment {
  id: number;
  content: string;
  parentId?: number | null;
  replies: Comment[];
  visibleRepliesCount?: number;
  user: string;
  avatar?: string;
}

interface UserVo {
  id:number;
  username: string;
  avatarPath: string;
  address: string;
  accountAge: number;
}

const props = defineProps<{ id: string }>();
const goods = ref<Goods | null>(null);
const goodsImages = ref<GoodsImage[]>([]);
const currentImageIndex = ref(0);
const comments = ref<Comment[]>([]);
const userVo = ref<UserVo | null>(null);
const categories = ref('');
const newComment = ref('');
const upperId = ref();
const isCollect = ref<boolean>()
const replyingToComment = ref<Comment | null>(null);
const router = useRouter();
const getGoodsByIdLink = "http://localhost:8080/goods/getGoodsById";
const getGoodsImgLink = "http://localhost:8080/goods/getGoodsImg";
const getCommentsLink = "http://localhost:8080/comment/getComment";
const submitCommentLink = "http://localhost:8080/comment/submitComment";
const getAvatarLink = "http://localhost:8080/user/getAvatar";
const getUpUserLink = "http://localhost:8080/user/getUpUser";
const getcategoriesLink = "http://localhost:8080/goods/getCategoriesNameById";
const addToCarLink = "http://localhost:8080/goods/addToCar";
const addFollowLink = "http://localhost:8080/user/follow";
const contactTheSellerLink = "http://localhost:8080/message/contactTheSeller";
const addCollectLink = "http://localhost:8080/collect/addCollect";
const deleteCollectLink = "http://localhost:8080/collect/deleteCollect";
const SelectCollectLink = "http://localhost:8080/collect/selectCollect";
const sendGoodsIdLink = "http://localhost:8080/goods/sendGoodsId";




const token = localStorage.getItem('token');
const loginUser = localStorage.getItem('username');
const userId =localStorage.getItem('userId')

const getGoodsById = async () => {
  try {
    const response = await axios.post(getGoodsByIdLink, props.id, {
      headers: { 'Content-Type': 'application/json' },
    });
    if (response.data.state) {
      goods.value = response.data.data;
    } else {
      console.error(response.data.errMessage);
    }
  } catch (error) {
    console.error(error);
  }
};

const getGoodsImg = async () => {
  try {
    const response = await axios.post(getGoodsImgLink, props.id, {
      headers: { 'Content-Type': 'application/json' },
    });
    if (response.data.state) {
      goodsImages.value = response.data.data;
    } else {
      console.error(response.data.errMessage);
    }
  } catch (error) {
    console.error(error);
  }
};

const processComments = (comments: Comment[]): Comment[] => {
  const commentMap: Record<number, Comment> = {};
  const result: Comment[] = [];
  comments.forEach(comment => {
    commentMap[comment.id] = {
      ...comment,
      replies: comment.replies || [],
      visibleRepliesCount: 1,
    };
  });

  comments.forEach(comment => {
    if (comment.parentId) {
      const parent = commentMap[comment.parentId];
      if (parent) {
        parent.replies?.push(commentMap[comment.id]);
      }
    } else {
      result.push(commentMap[comment.id]);
    }
  });
  return result;
};

const submitComment = async () => {
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try {
      let parentId = null;
      let replyUser = null;

      if (replyingToComment.value) {
        if (replyingToComment.value.parentId) {
          replyUser = replyingToComment.value.user;
          parentId = replyingToComment.value.parentId;
        } else {
          replyUser = replyingToComment.value.user;
          parentId = replyingToComment.value.id;
        }
      }else{
        replyUser = goods.value?.createUser; 
      }
      const commentDao = {
        content: newComment.value,
        user: loginUser,
        parentId: parentId,
        goodsId: props.id,
        replyUser: replyUser,
      };

      const response = await axios.post(submitCommentLink, commentDao, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });

      if (response.data.state) {
        // 成功提交后，清空评论框和回复状态
        newComment.value = '';
        replyingToComment.value = null;
        // 重新获取评论数据
        await getComments();
      } else {
        alert(response.data.errMessage);
      }
    } catch (error) {
      alert('提交评论失败: ' + error);
    }
  }
};


const replyToComment = (comment: Comment) => {
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    replyingToComment.value = comment;
    newComment.value = `@${comment.user}:`;
  }
};

const getAvatar = async (username: string): Promise<string | undefined> => {
  try {
    const response = await axios.post(getAvatarLink, { username }, {
      headers: { 'Content-Type': 'application/json' },
    });
    if (response.data.state) {
      return response.data.data; 
    } else {
      console.error(response.data.errMessage);
      return undefined;
    }
  } catch (error) {
    console.error(error);
    return undefined;
  }
};

const getComments = async () => {
  try {
    const response = await axios.post(getCommentsLink, props.id, {
      headers: { 'Content-Type': 'application/json' },
    });

    if (response.data.state) {
      const fetchedComments = processComments(response.data.data);

      const usernames = new Set(fetchedComments.map(comment => comment.user));
      const avatars: Record<string, string | undefined> = {};
      for (const username of usernames) {
        avatars[username] = await getAvatar(username);
      }
      for (const comment of fetchedComments) {
        comment.avatar = avatars[comment.user];
        for (const reply of comment.replies) {
          reply.avatar = avatars[reply.user];
        }
      }
      comments.value = fetchedComments;
    } else {
      console.error(response.data.errMessage);
    }
  } catch (error) {
    console.error(error);
  }
};

const getUpUser = async () => {
  if (!goods.value || !goods.value.createUser) {
    console.error('No valid user information available');
    return;
  }
  try {
    const response = await axios.post(getUpUserLink, goods.value.createUser, {
      headers: { 'Content-Type': 'application/json' },
    });
    upperId.value=response.data.data.id;
    if (response.data.state) {
      userVo.value = response.data.data; 
    } else {
      console.error(response.data.errMessage);
      return undefined;
    }
  } catch (error) {
    console.error(error);
    return undefined;
  }
};

const getcategorie = async () => {
  try {
    const response = await axios.post(getcategoriesLink, goods.value?.categoriesId, {
      headers: { 'Content-Type': 'application/json' },
    });

    if (response.data.state) {
      categories.value = response.data.data; 
    } else {
      console.error(response.data.errMessage);
      return undefined;
    }
  } catch (error) {
    console.error(error);
    return undefined;
  }
}

const addToCar = async()=>{
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try {
      const carObj = {
        id:null,
        goodsId: props.id,
        userId:userId
      };
      const response = await axios.post(addToCarLink, carObj, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
      const result = response.data;
      const state = result.state;
      const errMessage = result.errMessage;
      if(state){
        alert("添加成功!")
      }else{
        alert(errMessage)
      }
    } catch (error) {
      alert('添加失败: ' + error);
    }
  }
}

const follow = async()=>{
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try {
      const followDto ={
        userId:userId,
        followUser:upperId.value
      }
      const response = await axios.post(addFollowLink, followDto, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
      const result = response.data;
      const state = result.state;
      const errMessage = result.errMessage;
      if(state){
        alert("关注成功!")
      }else{
        alert(errMessage)
      }
    } catch (error) {
      alert('添加失败: ' + error);
    }
  }
}
const ContactTheSeller = async()=>{
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try{
      const ContactDto ={
        sendId:userId,
        receiverId:userVo.value?.id
      }
      const response = await axios.post(contactTheSellerLink, ContactDto, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
      const result = response.data;
      const state = result.state;
      const errMessage = result.errMessage;
      if(state){
        router.push({path:`/message/${upperId.value}`})
      }else{
        alert(errMessage)
      }
    } catch (error) {
      alert('出现问题了: ' + error);
    }
  }
}

const addCollect = async ()=>{
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try{
      const CollectDto ={
        userId:userId,
        goodsId:props.id
      }
      const response = await axios.post(addCollectLink, CollectDto, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
      const result = response.data;
      const state = result.state;
      const errMessage = result.errMessage;
      if (state) {
        isCollect.value=true;
      }else{
        alert(errMessage)
      }
    } catch (error) {
      alert('出现问题了: ' + error);
    }
  }
}

const deleteCollect = async ()=>{
  if (!token) {
    router.push({ name: 'Login' });
  } else {
    try{
      const CollectDto ={
        userId:userId,
        goodsId:props.id
      }
      const response = await axios.post(deleteCollectLink, CollectDto, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
      const result = response.data;
      const state = result.state;
      const errMessage = result.errMessage;
      if (state) {
        isCollect.value=false;
      }else{
        alert(errMessage)
      }
    } catch (error) {
      alert('出现问题了: ' + error);
    }
  }
}
SelectCollectLink

const SelectCollect = async ()=>{
    if(userId!=null){
      try{
      const CollectDto ={
        userId:userId,
        goodsId:props.id
      }
      const response = await axios.post(SelectCollectLink, CollectDto, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
      const result = response.data;
      const state = result.state;
      if (state) {
        isCollect.value=true;
      }
      else{
        isCollect.value=false;
      }} catch (error) {
      alert('出现问题了: ' + error);
    }
    }else{
      isCollect.value=false;
    } 
}
const showMoreReplies = (comment: Comment) => {
  comment.visibleRepliesCount = (comment.visibleRepliesCount ?? 1) + 3;
};

const showLessReplies = (comment: Comment) => {
  comment.visibleRepliesCount = 1;
};

const buy = async ()=>{
  if (goods.value) { // 确保 goods.value 不为 null
    try {
      // 跳转到购买页面并传递商品ID
      router.push({ name: 'Buy', query: { id: goods.value.id.toString() } });
    } catch (error) {
      console.error('跳转到购买页面失败:', error);
    }
  } else {
    alert('商品信息未加载完全');
  }
}

const sendGoodsId = async()=>{
  const HistoryDto=({
    userId:userId,
    goodsId:props.id
  })
  const response = await axios.post(sendGoodsIdLink, HistoryDto, {
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
      });
}

const nextImage = () => {
  currentImageIndex.value = (currentImageIndex.value + 1) % goodsImages.value.length;
};

const prevImage = () => {
  currentImageIndex.value = (currentImageIndex.value - 1 + goodsImages.value.length) % goodsImages.value.length;
};

const getGoods = (filterObject: { name: string; platform: string; sortType: string; categoriesId: number }) => {
  
};
onMounted(async () => {
  try {
    await getGoodsById();
    await getGoodsImg();
    await getComments();
    await nextTick(); 
    await getUpUser();
    await getcategorie();
    await SelectCollect();
    await sendGoodsId();

  } catch (error) {
    console.error('Error during mounted lifecycle:', error);
  }
});
</script>

